package com.sopaths.connect.weibo;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;

import com.qq.connect.utils.RandomStatusGenerator;
import com.sopaths.connect.ConnectAdapter;
import com.sopaths.contract.connect.OAuthToken;
import com.sopaths.contract.domain.LoginType;
import com.sopaths.contract.domain.User;
import com.sopaths.utility.web.WebUtil;

@Named("weiboConnectAdapter")
public class WeiboConnectAdapter implements ConnectAdapter {

	@Override
	public String getAuthorizeURL() {
		try {
			HttpServletRequest request = WebUtil.getHttpServletRequest();
			String state = RandomStatusGenerator.getUniqueState();
			((HttpServletRequest)request).getSession().setAttribute("weibo_connect_state", state);
			Oauth oauth = new Oauth();
			String url = oauth.authorize("code", state);
			return url;
		} catch (WeiboException ex) {
			throw new RuntimeException(ex);
		}
	}

	@Override
	public OAuthToken getToken() {
		try {
			HttpServletRequest request = WebUtil.getHttpServletRequest();
			String state = request.getParameter("state");
			validateState(state);
			String authorizationCode = request.getParameter("code");
			Oauth oauth = new Oauth();
			AccessToken weiboToken = oauth.getAccessTokenByCode(authorizationCode);
			OAuthToken token = new OAuthToken();
			token.setAccessToken(weiboToken.getAccessToken());
			token.setRefreshToken(weiboToken.getRefreshToken());
			token.setExpiredIn(Long.parseLong(weiboToken.getExpireIn()));
			token.setOpenID(weiboToken.getUid());
			return token;
		} catch (NumberFormatException | WeiboException ex) {
			throw new RuntimeException(ex);
		}
	}

	private void validateState(String state) {
		HttpServletRequest request = WebUtil.getHttpServletRequest();
		String sessionState = request.getSession().getAttribute("weibo_connect_state").toString();
		if (state == null || !state.equals(sessionState)) {
			throw new IllegalArgumentException("Mismatched authorization state. Session State: " + sessionState + ". Request state: " + state);
		}
	}

	@Override
	public User getUserInfo(OAuthToken token) {
		try {
			Users userService = new Users();
			userService.setToken(token.getAccessToken());
			weibo4j.model.User weiboUser = userService.showUserById(token.getOpenID());

			User user = new User();
			user.setUsername(weiboUser.getScreenName());
			user.setLoginType(LoginType.WEIBO);
			user.setToken(token);
			return user;
		} catch (WeiboException ex) {
			throw new RuntimeException(ex);
		}
	}

}
